package com.dba.example.gwt.client.activities;

import javax.inject.Inject;

import com.dba.example.gwt.client.beans.Company;
import com.dba.example.gwt.client.commands.CompanyGetCallback;
import com.dba.example.gwt.client.commands.CompanySaveCallback;
import com.dba.example.gwt.client.commands.ExampleCommandFactory;
import com.dba.example.gwt.client.places.CompanyEditPlace;
import com.dba.example.gwt.client.places.CompanyListPlace;
import com.dba.example.gwt.client.views.CompanyEditView;
import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.web.bindery.autobean.shared.AutoBean;

public class CompanyEditActivity extends AbstractActivity implements
		CompanyEditView.Presenter {

	private CompanyEditView view;

	private PlaceController pc;
	
	private ExampleCommandFactory cf;

	private CompanyEditPlace place;
	
	private AutoBean<Company> company;
	
	@Inject
	public CompanyEditActivity(CompanyEditView view, PlaceController pc, ExampleCommandFactory cf) {
		this.view = view;
		this.pc = pc;
		this.cf = cf;
	}

	public void setPlace(CompanyEditPlace place) {
		this.place = place;
	}

	@Override
	public void start(AcceptsOneWidget containerWidget, EventBus eventBus) {
		view.setPresenter(this);
		containerWidget.setWidget(view.asWidget());
		
		getCompany(place.getId());
	}
	
	@Override
	public void save() {
		boolean errors = view.flush();
		if (errors) {
			Window.alert("Errors");
			return;
		}
		
		Command c = cf.companySave(company, new CompanySaveCallback() {
			@Override
			public void success(AutoBean<Company> company) {
				pc.goTo(new CompanyListPlace());
			}

			@Override
			public void error(String error) {
			}
		});
		c.execute();
	}
	
	@Override
	public void cancel() {
		
	}
	
	@Override
	public void goTo(Place place) {
		pc.goTo(place);
	}
	
	private void getCompany(Integer id) {
		Command c = cf.companyGet(id, new CompanyGetCallback() {
			@Override
			public void success(AutoBean<Company> company) {
				edit(company);
			}
			
			@Override
			public void error(String error) {
			}
		});
		c.execute();
	}
	
	private void edit(AutoBean<Company> company) {
		this.company = company;
		view.edit(this.company.as());
	}

	public void onStop() {
	}

}
